package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.LRUMap;

import com.conversationboard.cache.VoterCache;
import com.conversationboard.config.Configuration;
import com.conversationboard.model.propertybag.PropertyBag;
import com.conversationboard.serialisation.XmlSerialiser;

@WebServlet(name = "AdminStoreVotesControllerServlet", urlPatterns = "/Admin/AdminStoreVotesControllerServlet")
public class AdminStoreVotesControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -6051675005483650606L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			/* Serialise voter cache */

			LRUMap voterCache = VoterCache.getVoterCache();
			XmlSerialiser<LRUMap> serialiser = new XmlSerialiser<LRUMap>();

			String xml = null;

			synchronized (voterCache) {
				xml = serialiser.serialise(voterCache);
			}

			/* Put it in the property bag */

			if (xml != null) {
				PropertyBag.put("votercache", xml);
			}

			response.sendRedirect(Configuration.getInstance().getRoot() + "/index.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
